<template>
  <a-modal
    title="学生调课"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleCancel"
    @cancel="handleCancel"
    :footer="null"
  >
    <div>
      <a-card :bordered="false" :bodyStyle="tstyle">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="16" :sm="24">
            <span class="base-title">{{baseInfo.userInfo.name}} 同学，
              <template v-if="baseInfo.stuTagDesc">
                您是{{baseInfo.stuTagDesc}}学生，
              </template>
              已为您列出当前开放选课的课程
            </span>
              </a-col>
              <a-col :md="8" :sm="24">
                选课校验：
                <a-tag color='red' v-if="checkResult===0">
                  不合格
                </a-tag>
                <a-tag color='red' v-if="checkResult===0 && checkReason">
                  {{checkReason}}
                </a-tag>
                <a-tag color='green' v-if="checkResult===1">
                  合格
                </a-tag>
              </a-col>
              <a-col :md="16" :sm="24">
                <span class="base-title">{{baseInfo.schoolYear?baseInfo.schoolYear.name:'无'}}</span>
                {{baseInfo.schoolTerm?baseInfo.schoolTerm.name:'无'}}
              </a-col>
              <a-col :md="8" :sm="24">
                选课时间:
                  {{baseInfo.coursePublishList[0].selectionStartDate}} ~ {{baseInfo.coursePublishList[0].selectionEndDate}}
              </a-col>
              <a-col :md="16" :sm="24">
                <a-form-item label="请选择当前开放的实验课程">
                  <a-select v-model="queryParam.coursePublishId" allow-clear placeholder="请选择实验课程"
                            @change="changeCourse" disabled="true">
                    <a-select-option v-for="(item,index) in baseInfo.coursePublishList" :key="index" :value="item.id">
                      {{item.courseName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-button type="primary" @click="checkCourseSelection">校验选课</a-button>
                <a-popconfirm
                  title="确定要清空选课吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="emptyCourseSelection"
                >
                  <a-button style="margin-left: 8px" type="danger">清空选课</a-button>
                </a-popconfirm>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-card>
      <a-card :bordered="false">
        <a-table
          bordered
          ref="table"
          :columns="columns"
          :dataSource="loadData"
          :loading="tableLoading"
          :pagination="false"
          :rowKey="(record,index) => record.index"
        >
        <span slot="frequencyDay" slot-scope="text, record">
          <a-tag color="orange">{{'星期'+text}}</a-tag>
        </span>

          <span v-for="(item,index) in cryData.coursePublishFrequencyList"
                :slot="['frequencyIndex-',item.frequencyIndex].join('')" slot-scope="text, record">
          <template v-if="text">
            <a-tag :color="text.fullFlag?'red':'green'">
              <a-badge :dot="checkChooseByStu(record.id,record.frequencyDay,item.frequencyIndex)===0">
                已选{{text.courseSelectionNum}}人
              </a-badge>
            </a-tag>
            <a-popconfirm
              title="确定选择本次实验课程选课吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="toCourseSelection(record,text)"
            >
              <a-button type="primary" size="small" v-if="!text.courseSelectionId && !text.fullFlag">
                确定
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              title="确定取消本次实验课程选课吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="cancelCourseSelection(text.courseSelectionId)"
            >
              <a-button type="danger" size="small" v-if="text.courseSelectionId">
                取消
              </a-button>
            </a-popconfirm>

          </template>
        </span>
        </a-table>
      </a-card>
    </div>
  </a-modal>
</template>
<script>
  import {
    cancelCourseSelection,
    checkCourseSelection,
    emptyCourseSelection,
    getCourseSelectionBaseInfo,
    getCourseSelectionCryInfo,
    toCourseSelection
  } from '@/api/modular/system/courseSelectionManage'

  export default {
    components: {},
    data() {
      return {
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        visible: false,
        confirmLoading: false,
        queryParam: {
          coursePublishId: ''
        },
        baseInfo: '',
        cryColumns: [
          {
            title: '实验模块',
            dataIndex: 'moduleName',
            customRender(_, row) {
              return {
                children: row.moduleName,
                attrs: {
                  rowSpan: row.rowSpan
                }
              }
            }
          },
          {
            title: '模块选课要求',
            dataIndex: 'moduleDesc',
            customRender(_, row) {
              return {
                children: row.moduleDesc,
                attrs: {
                  rowSpan: row.rowSpan
                }
              }
            }
          },
          {
            title: '实验项目',
            dataIndex: 'projectName',
            customRender(_, row) {
              return {
                children: row.projectName,
                attrs: {
                  rowSpan: row.rowSpan
                }
              }
            }
          },
          {
            title: '实验教室',
            dataIndex: 'classroomName'
          },
          {
            title: '任课老师',
            dataIndex: 'teacherName'
          },
          {
            title: '开课日期',
            dataIndex: 'frequencyDay',
            scopedSlots: { customRender: 'frequencyDay' }
          },
          {
            title: '限选人数',
            dataIndex: 'maxStudents'
          }
        ],
        // 表头
        columns: [],
        loadData: '',
        tableLoading: false,
        cryData: '',
        checkResult: '',
        param: '',
        checkReason: '',
        //第一次打开
        firstOpen: false,
        //原始学生选择数据
        origStuCsData: ''
      }
    },
    created() {
      this.initColumns()
    },
    methods: {
      handleCancel() {
        this.visible = false
        this.$emit('ok')
      },
      open(param) {
        this.visible = true
        this.firstOpen = true
        this.queryParam.coursePublishId = param.coursePublishId
        this.param = param
        this.getBaseInfo(param)
        this.changeCourse(param)
      },
      initColumns() {
        let tempColumns = []
        this.cryColumns.map((item) => {
          tempColumns.push(item)
        })
        this.columns = tempColumns
      },
      getBaseInfo(param) {
        getCourseSelectionBaseInfo({
          coursePublishId: param.coursePublishId,
          userId: param.studentId,
          schoolYearId: param.schoolYearId,
          schoolTermId: param.schoolTermId
        }).then((res) => {
          if (res.success) {
            this.baseInfo = res.data
          } else {
            this.$message.error('获取选课基础信息异常：' + res.message)
          }
        })
      },
      changeCourse(param) {
        this.tableLoading = true
        getCourseSelectionCryInfo({
          coursePublishId: param.coursePublishId,
          userId: param.studentId
        }).then((res) => {
          if (res.success) {
            this.initColumns()
            this.cryData = res.data
            this.appendColumns(res.data.coursePublishFrequencyList)
            this.loadData = res.data.courseScheduleVoList
            if (this.firstOpen) {
              //记录下原始数据
              this.origStuCsData = res.data.courseScheduleVoList
            }
          } else {
            this.$message.error('获取选课内容信息异常：' + res.message)
          }
        }).finally(() => {
          this.tableLoading = false
          //让后续刷新不刷原始数据
          this.firstOpen = false
        })
      },
      appendColumns(list) {
        list?.map((item) => {
          this.columns.push({
            title: '第' + item.frequencyIndex + '轮（' + item.weekStart + '-' + item.weekEnd + '周）',
            dataIndex: 'frequencyIndex-' + item.frequencyIndex,
            scopedSlots: { customRender: 'frequencyIndex-' + item.frequencyIndex }
          })
        })
      },
      toCourseSelection(record, coursePublishFrequencyItem) {
        toCourseSelection({
          coursePublishId: coursePublishFrequencyItem.coursePublishId,
          courseScheduleId: coursePublishFrequencyItem.courseScheduleId,
          courseScheduleFrequencyId: coursePublishFrequencyItem.courseScheduleFrequencyId,
          frequencyIndex: coursePublishFrequencyItem.frequencyIndex,
          frequencyDay: record.frequencyDay,
          studentId: this.param.studentId
        }).then((res) => {
          if (res.success) {
            this.changeCourse(this.param)
            this.$message.success('添加实验选课成功')
            this.checkCourseSelection()
          } else {
            this.$message.error('添加实验选课失败：' + res.message)
          }
        })
      },
      cancelCourseSelection(courseSelectionId) {
        cancelCourseSelection({
          id: courseSelectionId,
          studentId: this.param.studentId
        }).then((res) => {
          if (res.success) {
            this.changeCourse(this.param)
            this.$message.success('取消实验选课成功')
            this.checkCourseSelection()
          } else {
            this.$message.error('取消实验选课失败：' + res.message)
          }
        })
      },
      checkCourseSelection() {
        if (this.queryParam.coursePublishId) {
          checkCourseSelection({
            coursePublishId: this.queryParam.coursePublishId,
            userId: this.param.studentId
          }).then((res) => {
            if (res.success) {
              this.checkResult = res.data.checkResult
              if (res.data.checkResult === 0) {
                this.checkReason = '至少选择' + res.data.targetNum + '个实验项目'
              } else {
                this.checkReason = ''
              }
            } else {
              this.$message.error('选课校验失败：' + res.message)
            }
          })
        } else {
          this.$message.error('请先选择一个实验课程！')
        }
      },
      emptyCourseSelection() {
        if (this.queryParam.coursePublishId) {
          emptyCourseSelection({
            coursePublishId: this.queryParam.coursePublishId,
            userId: this.param.studentId
          }).then((res) => {
            if (res.success) {
              this.changeCourse(this.param)
              this.$message.success('清空实验选课成功')
              this.checkCourseSelection()
            } else {
              this.$message.error('清空实验选课失败：' + res.message)
            }
          })
        } else {
          this.$message.error('请先选择一个实验课程！')
        }
      },
      checkChooseByStu(courseScheduleId, frequencyDay, frequencyIndex) {
        if (this.origStuCsData && this.origStuCsData.filter((data) => data.id === courseScheduleId && data.frequencyDay === frequencyDay).length > 0) {
          return this.origStuCsData && this.origStuCsData.filter((data) => data.id === courseScheduleId && data.frequencyDay === frequencyDay)[0]['frequencyIndex-' + frequencyIndex].optType
        } else {
          return undefined
        }
      }
    }
  }
</script>
<style lang="less">
  .base-title {
    font-weight: bold;
    color: #015478;
  }
</style>